#!/usr/bin/env python

import numpy as np
import matplotlib
# CocoaAgg FltkAgg MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS
# PDF SVG Template
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt 

sampling_freq = 44100. / 2.
slice_size = 2048
slice_interval_s = slice_size / sampling_freq


def getFloatSeries(filename):
  rows = open(filename).readlines()
  values = [[float(n) for n in row.split()] for row in rows]
  transposed = map(list, zip(*values))
  return np.array(transposed)

td = getFloatSeries('/Users/philip/tmp/time_domain.txt')[0]
times = np.arange(len(td)) / sampling_freq

expected_times = getFloatSeries('/Users/philip/tmp/expected_timestamps')[0] + slice_interval_s / 2.
achieved_times = getFloatSeries('/Users/philip/tmp/achieved_timestamps')[0]
detector_data = getFloatSeries('/Users/philip/tmp/EdgeDetector_debug')
detector_time = detector_data[0]
detector_level = detector_data[1] / 50.
detector_ema = detector_data[2] / 50.
#detector_fall = detector_data[3] * 1000.
fall_threshold = detector_data[4] / 50.
#detector_fallen = detector_data[5] * 1000.
rise_threshold = detector_data[6] / 50.
last_peak = detector_data[7] / 50.
fd = np.fft.fft(td[8000:])
fda = np.abs(fd)
#plt.subplot(2,1,1)
x0 = len(times)/6
x1 = len(times)/3
#plt.plot(times[x0:x1], td[x0:x1])
plt.plot(times, td, '.', markersize=0.2, color='black')
plt.plot(expected_times, np.arange(len(expected_times)), '+', label='expected', markeredgewidth=2.0, markersize=10.0)
plt.plot(achieved_times, np.arange(len(achieved_times)), 'x', label='achieved', markeredgewidth=2.0, markersize=10.0)
plt.plot(detector_time, detector_level, 'o-', label='detector level')
plt.plot(detector_time, detector_ema, '-', label='detector ema')
plt.plot(detector_time, fall_threshold, 'o-', label='detector fall threshold')
#plt.plot(detector_time, detector_fall, '-', label='detector fall')
#plt.plot(detector_time, detector_fallen, '-', label='detector fallen')
plt.plot(detector_time, rise_threshold, 'o-', label='rise threshold')
#plt.plot(detector_time, rise_threshold, 'o-', label='last peak')
plt.xticks(np.arange(100)*slice_interval_s)
plt.grid(True, linestyle='-', color='0.75')
plt.legend()
plt.title('time domain')
#plt.subplot(2,1,2)
#plt.plot(fda[:2000])
#plt.title('frequency domain')

plt.show()
